﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.ShenPi;
using B.S.BasicData.Domian.Entities.Account;
using B.S.BasicData.Domian.Entities.shenpi;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Read.Application.Handler.ShenPi
{
    public class ShenpiCreateHandler : IRequestHandler<ShenpiCreateCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<LeaveModel> leaveRepo;
        private readonly IMapper mapper;

        public ShenpiCreateHandler(IBaseRepository<LeaveModel>leaveRepo,IMapper mapper)
        {
            this.leaveRepo = leaveRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(ShenpiCreateCommand request, CancellationToken cancellationToken)
        {
            var res=new ApiResult<int>();
            var leave = leaveRepo.GetAll().Where(x => x.Name == request.Name).FirstOrDefault();
            if (leave != null)
            {
                res.Message = "用户名不能重复";
                res.Code = ApiEnum.File;
                return Task.FromResult(res);
            }
            var entity = mapper.Map<LeaveModel>(request);
            var r = leaveRepo.Add(entity).Result;
            if (r > 0)
            {
                res.Message = "新增成功";
                res.Code = ApiEnum.Ok;
                res.Data = r;
            }
            else
            {
                res.Message = "新增失败";
                res.Code = ApiEnum.Error;
                res.Data = r;
            }
            return Task.FromResult(res);
        }
    }
}
